﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using StuMana.Services;
using System.Xml;
using System.Security.Cryptography;

namespace StuMana.UI
{
    public partial class Login : Office2007Form
    {
       public class Level
        {
            public string _name;
            public int _code;

            public Level()
            {

            }

            public Level( string name, int code)
            {
                _name = name;
                _code = code;
            }
        }
      public  class Account
        {
            public string _username;
            public string _password;
            public string _name;
            public string _birthDay;
            public string _gender;
            public int _level;

            public Account()
            {
                _username = "";
                _password = "";
                _name = "";
                _birthDay = "";
                _gender = "";
                _level=-1;
            }

            public Account(string username, string password, string name,string birthDay, string gender, int level)
            {
                _username = username;
                _password = password;
                _name = name;
                _birthDay = birthDay;
                _gender = gender;
                _level = level;
            }
        }

        public Services.SL025M rfid_reader = new Services.SL025M();
        public Services.COM connect;

        private Font fontForAll = null;
        private StyleManager managerStyle = new DevComponents.DotNetBar.StyleManager();
        public void ReadSetting()
        {
            XmlReader reader = XmlReader.Create("Settings.xml");
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element
                && reader.Name == "font")
                {
                    string name = reader.GetAttribute(0).ToString();
                    string style = reader.GetAttribute(1).ToString();
                    float size = float.Parse(reader.GetAttribute(2).ToString());

                    if (style == "Bold")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Italic")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Regular")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Strikeout")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Strikeout, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Underline")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                        if (reader.Name == "managerstyle" && reader.NodeType == XmlNodeType.Element)
                        {
                            reader.Read();
                            string stylemana = reader.Value.ToString();

                            if (stylemana == "Office2007Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Blue;
                            if (stylemana == "Office2007Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Silver;
                            if (stylemana == "Office2007Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Black;
                            if (stylemana == "Windows7Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Windows7Blue;
                            if (stylemana == "Office2007VistaGlass")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007VistaGlass;
                            if (stylemana == "Office2010Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Silver;
                            if (stylemana == "Office2010Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Blue;
                            if (stylemana == "Office2010Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Black;
                        }
                    }
                }
            }
            reader.Close();
        }

        public void ConfigSetting()
        {
            ReadSetting();
            for (int i = 0; i < Controls[0].Controls[0].Controls[0].Controls.Count; i++)
            {
                if (Controls[0].Controls[0].Controls[0].Controls[i] is LabelX)
                {
                    Controls[0].Controls[0].Controls[0].Controls[i].Font = fontForAll;
                }
            }

            styleManager1 = managerStyle;
        }

        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {
            ConfigSetting();
            LoadAllLevel();
            int wPanel = this.gPanelMiddle.Size.Width;
            int hPanel = this.gPanelMiddle.Size.Height;

            int w2Panel = ((int)(wPanel / 2));
            int h2Panel = ((int)(hPanel / 2));

            int wPanel2 = this.gPanelLogin.Size.Width;
            int hPanel2 = this.gPanelLogin.Size.Height;

            int w2Panel2 = ((int)(wPanel2 / 2));
            int h2Panel2 = ((int)(hPanel2 / 2));

            int x = w2Panel - w2Panel2;
            int y = h2Panel - h2Panel2;

            this.gPanelLogin.Location = new Point(x, y);
         //   txtUserName.Enabled = false;
        //    llblLogOut.Visible = false;            
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
            Application.ExitThread();
            Application.Exit();
            //this.Close();
        }

        private void LoadAllLevel()
        {        
            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                cmd.CommandText = "SELECT *  FROM Level ";
                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);
                cmbAccountLevel.DataSource = ds.Tables[0].DefaultView;
                cmbAccountLevel.DisplayMember = "Name";
                cmbAccountLevel.ValueMember = "ID";              
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }           
        }

        public bool CheckInput()
        {
            bool kq = false;
            if (txtUserName.Text == "")
            {
                MessageBoxEx.Show("Username is blank ", "Warning  !!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (txtPassword.Text == "")
            {
                MessageBoxEx.Show("Password is blank ", "Warning  !!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            kq = true;
            return kq;
            
        }
        private Account CheckDatabase(string userName,string passWord)
        {
            passWord = Md5.EncryptString(passWord);
            Account kq = new Account();
            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                cmd.CommandText = "SELECT *  FROM Account WHERE UserName = '" + userName.ToString() +"' and Password = '"+passWord.ToString()+"'";
                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    kq._username = ds.Tables[0].Rows[0]["UserName"].ToString();
                    kq._password = ds.Tables[0].Rows[0]["Password"].ToString();
                    kq._level = int.Parse(ds.Tables[0].Rows[0]["Level"].ToString());
                }             
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }
            return kq;
        }

        public void ShowForm(object sender, FormClosedEventArgs e)
        {
            this.Visible = true;
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            ConfigSetting();
            if (CheckInput())
            {
                Account acc = new Account();
                acc = CheckDatabase(txtUserName.Text,txtPassword.Text);
                if (acc._level == 0)  // admin 
                {
                    // open all tab 
                    txtPassword.Enabled = false;
                    llblLogOut.Visible = true;
                    btnLogin.Enabled = false;
                    foreach (Office2007Form frm in Application.OpenForms)
                    {
                        if (frm is UI.MainForm)
                        {
                            MainForm obj = (MainForm)frm;
                            obj.Level = 0;
                            obj.AdminLogin();
                            return;
                        }
                    }
                }
                else if (acc._level == 1) // 1 staff 1
                {
                    txtPassword.Enabled = false;
                    llblLogOut.Visible = true;
                    btnLogin.Enabled = false;
                    foreach (Office2007Form frm in Application.OpenForms)
                    {
                        if (frm is UI.MainForm)
                        {
                            MainForm obj = (MainForm)frm;
                            obj.Level = 1;
                            obj.Staff1Login();
                            return;
                        }
                    }
                }
                else if (acc._level == 2) // staff 2 
                {
                    txtPassword.Enabled = false;
                    llblLogOut.Visible = true;
                    btnLogin.Enabled = false;
                    foreach (Office2007Form frm in Application.OpenForms)
                    {
                        if (frm is UI.MainForm)
                        {
                            MainForm obj = (MainForm)frm;
                            obj.Staff2Login();                          
                        }
                    }
                   
                }
                else if (acc._level == 3) // Teacher
                {
                    txtPassword.Enabled = false;
                    llblLogOut.Visible = true;
                    btnLogin.Enabled = false;
                    foreach (Office2007Form frm in Application.OpenForms)
                    {
                        if (frm is UI.MainForm)
                        {
                            MainForm obj = (MainForm)frm;
                            obj.TeacherLogin();
                            return;
                        }
                    }
                }
                else if (acc._level == 4) // Security Guard 
                {
                    txtPassword.Enabled = false;
                    llblLogOut.Visible = true;
                    btnLogin.Enabled = false;
                    foreach (Office2007Form frm in Application.OpenForms)
                    {
                        if (frm is UI.MainForm)
                        {
                            MainForm obj = (MainForm)frm;
                            obj.SecurityGuardLogin();
                            return;
                        }
                    }
                }
                else
                {
                    MessageBoxEx.Show("invalid account ","Error !!",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    txtPassword.Text = "";
                }
            }
        }

        private void txtPassword_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (CheckInput())
                {
                    Account acc = new Account();
                    acc = CheckDatabase(txtUserName.Text, txtPassword.Text);
                    if (acc._level == 0)  // admin 
                    {
                        // open all tab 
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.AdminLogin();
                                return;
                            }
                        }
                        
                    }
                    else if (acc._level == 1) // 1 staff 1
                    {
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.Staff1Login();
                                return;
                            }
                        }                     
                    }
                    else if (acc._level == 2) // staff 2 
                    {
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.Staff2Login();
                                return;
                            }
                        }
                    }
                    else if (acc._level == 3) // Teacher
                    {
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.TeacherLogin();
                                return;
                            }
                        }
                    }
                    else if (acc._level == 4) // Security Guard 
                    {
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.SecurityGuardLogin();
                                return;
                            }
                        }
                    }
                    else
                    {
                        MessageBoxEx.Show("invalid account ", "Error !!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtPassword.Text = "";
                    }
                }
            }
        }

        private void Login_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (CheckInput())
                {
                    Account acc = new Account();
                    acc = CheckDatabase(txtUserName.Text, txtPassword.Text);
                    if (acc._level == 0)  // admin 
                    {
                        // open all tab 
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.AdminLogin();
                                return;
                            }
                        }

                    }
                    else if (acc._level == 1) // 1 staff 1
                    {
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.Staff1Login();
                                return;
                            }
                        }
                    }
                    else if (acc._level == 2) // staff 2 
                    {
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.Staff2Login();
                                return;
                            }
                        }
                    }
                    else if (acc._level == 3) // Teacher
                    {
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.TeacherLogin();
                                return;
                            }
                        }
                    }
                    else if (acc._level == 4) // Security Guard 
                    {
                        txtPassword.Enabled = false;
                        llblLogOut.Visible = true;
                        btnLogin.Enabled = false;
                        foreach (Office2007Form frm in Application.OpenForms)
                        {
                            if (frm is UI.MainForm)
                            {
                                MainForm obj = (MainForm)frm;
                                obj.SecurityGuardLogin();
                                return;
                            }
                        }
                    }
                    else
                    {
                        MessageBoxEx.Show("invalid account ", "Error !!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtPassword.Text = "";
                    }
                }
            }
        }

        private void Login_Resize(object sender, EventArgs e)
        {
            int wPanel = this.gPanelMiddle.Size.Width;
            int hPanel = this.gPanelMiddle.Size.Height;

            int w2Panel = ((int)(wPanel / 2));
            int h2Panel = ((int)(hPanel / 2));

            int wPanel2 = this.gPanelLogin.Size.Width;
            int hPanel2 = this.gPanelLogin.Size.Height;

            int w2Panel2 = ((int)(wPanel2 / 2));
            int h2Panel2 = ((int)(hPanel2 / 2));

            int x = w2Panel - w2Panel2;
            int y = h2Panel - h2Panel2;

            this.gPanelLogin.Location = new Point(x, y);
        }

        private void Login_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
            Application.ExitThread();
            Application.Exit();
        }

        private void Login_FormClosing(object sender, FormClosingEventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
            Application.ExitThread();
            Application.Exit();
        }

        private void cmbAccountLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtUserName.Text = cmbAccountLevel.Text.ToString();
        }

        private void llblLogOut_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtPassword.Enabled = true;
            btnLogin.Enabled = true ;
            llblLogOut.Visible = false;
            txtUserName.Text = "";
            txtPassword.Text = "";
            foreach (Office2007Form frm in Application.OpenForms)
            {
                if (frm is UI.MainForm)
                {
                    MainForm obj = (MainForm)frm;
                    obj.StartLogin();
                    return;
                }
            }
        }
    }
}
